package com.tomkk;

import com.google.gson.Gson;
import com.tomkk.entity.NewsListItem;
import com.tomkk.utils.Error;
import com.tomkk.utils.MysqlOperation;
import com.tomkk.utils.Success;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

/**
 * Created by Tomkk on 2016/5/31.
 */
@WebServlet(name = "GetAllNewsServlet",urlPatterns = "/getAllNews")
public class GetAllNewsServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        String sql = "SELECT news_title,news_id,nickname,news_publish_time,headimage FROM news,user WHERE news_isuse = true AND news.user_id = user.user_id;";
        MysqlOperation operation = new MysqlOperation();
        operation.checkConn();
        ResultSet resultSet = operation.query(sql);
        Gson gson = new Gson();
        String json = null;
        ArrayList<NewsListItem> newsListItems = new ArrayList<>();
        if(resultSet == null){
            json = gson.toJson(new Error(2,"服务器错误"));
        }else{
            try {
                while(resultSet.next()) {
                    String news_title = resultSet.getString("news_title");
                    int news_id = resultSet.getInt("news_id");
                    String nickname = resultSet.getString("nickname");
                    String news_publish_time = resultSet.getString("news_publish_time");
                    String headimage = resultSet.getString("headimage");
                    NewsListItem item = new NewsListItem(news_id,news_title,nickname,news_publish_time,headimage);
                    newsListItems.add(item);
                }
                json = gson.toJson(new Success(0,newsListItems));
            } catch (SQLException e) {
                e.printStackTrace();
                json = gson.toJson(new Error(2,"服务器错误"));
            }
        }
        PrintWriter writer = response.getWriter();
        writer.print(json);
        writer.flush();
        try {
            operation.closeDB();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
